package cn.buaa.anniversary.helper;


import cn.buaa.anniversary.Utils.ImgUtil;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.buaa.anniversary.Utils.TextUtil;
import cn.buaa.anniversary.model.Point;
/**
 * Created this one by HMH on 2017/5/5.
 */
public class ImgHelper {

    public static BufferedImage magic(String backGround, String text, String qrImage, String font, int fontSize, Color color, Point textPoint, Point qrPoint, String savePath, double zoom) throws IOException {
        return magic(new File(backGround), text, new File(qrImage), font, fontSize, color, textPoint, qrPoint,zoom);
    }

    public static BufferedImage magic(File backGround, String text, String qrImage, String font, int fontSize, Color color, Point textPoint, Point qrPoint, String savePath, double zoom) throws IOException {
        return magic(backGround, text, new File(qrImage), font, fontSize, color, textPoint, qrPoint,zoom);

    }

    public static BufferedImage magic(File backGround, String text, File qrImage, String fontName,int fontSize,Color color, Point textPoint,Point qrPoint,double zoom) throws IOException {
        Font font = new Font(fontName, Font.PLAIN, fontSize);
        return magic(backGround, text, qrImage, font, color, textPoint, qrPoint,zoom);
    }

    public static BufferedImage magic(File backGround, String text, File qrImage, Font font,Color color, Point textPoint,Point qrPoint,double zoom) throws IOException {
        //读取两个图像
        BufferedImage bufferBackground = ImageIO.read(backGround);
        BufferedImage bufferQRImage = ImageIO.read(qrImage);
        bufferQRImage = ImgUtil.zoomImage(bufferQRImage, zoom);
        //融合图像
        bufferBackground = ImgUtil.mixture(bufferBackground, bufferQRImage, qrPoint.getX(), qrPoint.getY());
        //生成文字
        bufferBackground = ImgUtil.addText(bufferBackground, text, font, textPoint.getX(), textPoint.getY(), color);
        return bufferBackground;
    }

    /**
     * 计算文字居中放置时 左上角X坐标
     * @param width 图片宽度
     * @param text 文本
     * @param fontSize 字体大小 单位： pix
     * @param includeChineseChars 其他需要作为中文的字符列表 比如中文全角符号等
     * @return 左上角X坐标
     */
    public static int computeTextPointForCenter(int width, String text,int fontSize,List<Character> includeChineseChars) {
        int length = 0;
        for (char c : text.toCharArray()) {
            if (TextUtil.isChineseChar(c, includeChineseChars)) {
                length += fontSize;
            } else {
                length += fontSize / 2;
            }
        }
        return (width - length) / 2 + 20;
    }

}